import io from 'socket.io-client'
import {Observer, noop} from '../core/util'
import config from '../../config.json'

let socket;
let socketEvent = {};
// 监听socket事件
const onEvent = (event, cb) => {
  if(event === 'lockInfo') return socket.on(event, cb);
  if(!socketEvent[event]) socketEvent[event] = [];
  if(cb) socketEvent[event].push(cb);
}
const dispatch = (msg) => {
  if(msg && msg.event) {
    let arr = socketEvent[msg.event] || [];
    for(let i = 0, len = arr.length; i < len; i++) {
      arr[i](msg.message);
    }
  }
}
// 触发socket事件
const emitEvent = (event, message) => {
  if(event === 'lockInfo') return socket.emit(event, message);
  socket.emit('change', {event, message});
}
// 编辑上锁
const lock = (lockInfo, succ = noop, err = noop, timeout = noop) => {
  function remove() {
    socket.off('locked', lockErr);
    socket.off('lockInfo', lockSucc);
    clearTimeout(timer);
  }
  function lockErr(user) {
    err(user);
    remove();
  }
  function lockSucc() {
    succ();
    remove();
  }
  var timer = setTimeout(() => {
    timeout();
    remove();
  }, 5000)
  socket.on('locked', lockErr);
  socket.on('lockInfo', lockSucc);
  socket.emit('lock', lockInfo);
}
// 解锁
const unlock = (id) => {
  socket.emit('unlock', id);
}

const connectSocket = (userId) => {
  socket = io(`http://okms.dev.cnki.net:${config['socket_port']}`, {
    query: {
      room: window.bookId,
      user: userId
    }
  });
  socket.on('change', dispatch);
}

export {connectSocket, onEvent, emitEvent, lock, unlock}